package ULHT.LIG2N1.RC.CLIENT;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UDPThread extends Thread {

    private static int UDPport = 9031;
    private static String host = "localhost";
    private DatagramSocket socket;
    private boolean stopped = false;

    public UDPThread(DatagramSocket ds) throws SocketException {
        this.socket = ds;
        sendNotify();
    }

    public void halt() {
        this.stopped = true;
    }

    @Override
    public void run() {
        byte[] buffer = new byte[65507];
        while (true) {
            if (stopped) {
                return;
            }
            DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
            try {
                socket.receive(dp);
                String s = new String(dp.getData(), 0, dp.getLength());
                System.out.println(s);
                //Thread.yield();
            } catch (IOException e) {
                System.err.println(e);
            }
        }
    }

    private void sendNotify() {
        String message = "HELLO";
        DatagramPacket outPacket;					
        try {
            outPacket = new DatagramPacket(message.getBytes(), message.length(), InetAddress.getByName(host), UDPport);
            this.socket.send(outPacket);
        } catch (Exception ex) {
            Logger.getLogger(UDPThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
